package com.zn.opit.shirodemo.config;

import com.zn.opit.shirodemo.converter.String2DateConverter;
import com.zn.opit.shirodemo.converter.String2LocalDateConverter;
import com.zn.opit.shirodemo.converter.String2LocalDateTimeConverter;
import com.zn.opit.shirodemo.converter.String2LocalTimeConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    /**
     * 全局跨域处理
     *
     * @param registry Cross-Origin Resource Sharing Registry 资源共享注册
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
                .allowCredentials(true)
                .maxAge(3600)
                .allowedHeaders("*");
    }

    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new String2LocalDateConverter());
        registry.addConverter(new String2LocalDateTimeConverter());
        registry.addConverter(new String2LocalTimeConverter());
        registry.addConverter(new String2DateConverter());
    }

    @Bean(name = "multipartResolver")
    public CommonsMultipartResolver getCommonsMultipartResolver() {
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
        multipartResolver.setMaxUploadSize(419430400);
        multipartResolver.setMaxInMemorySize(419430400);
        multipartResolver.setDefaultEncoding("UTF-8");
        return multipartResolver;
    }
}
